package com.thread.exe;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Renderer {
	
	private final ExecutorService executor = Executors.newCachedThreadPool();
	
	void renderPage(CharSequence source) {
		List<ImageInfo> iis = getImageInfo(source);
		CompletionService<ImageData> completionService = new ExecutorCompletionService<>(executor);
		for (ImageInfo i : iis) {
			completionService.submit(new Callable<ImageData>() {
				@Override
				public ImageData call() throws Exception {
					return i.downLoad();
				}
			});
		}

		renderText(source);
		try {
			for (int i = 0; i < iis.size(); i++) {
				Future<ImageData> future = completionService.take();
				renderImage(future.get());
			}
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
		} catch (ExecutionException e) {
			throw launderThrowable(e.getCause());
		}
	}
	

	public static RuntimeException launderThrowable(Throwable t) {
        if(t instanceof RuntimeException)
            return (RuntimeException) t;
        else if(t instanceof Error)
            throw (Error) t;
        else
            throw new IllegalStateException("Not unchected", t);
   }

	
	private void renderImage(ImageData imageData) {
		// 处理图片
	}

	private void renderText(CharSequence source) {
		// 处理文本
	}

	private List<ImageInfo> getImageInfo(CharSequence source) {
		return new ArrayList<ImageInfo>();
	}

	private class ImageInfo {

		public ImageData downLoad() {
			return new ImageData();
		}
		//图像下载地址
	}
	
	private class ImageData {
		//图像信息
	}
}
